<!-- 上架商品页面 -->
<template>
	<!-- 上传图片模块  -->
	<view class="goods-top">
		<!-- 标题部分 -->
		<view><input v-model="goods_title" type="text" placeholder="请输入商品标题" placeholder-class="pl-text"></view>
		<!-- 图片部分 -->
		<view class="goods-image">
			<!-- 上传的图片 -->
			<view class="upload-image" v-if="coverImg.length > 0" v-for="(item,index) in coverImg " :key="index">
				<image @click="previewImg(item.imgUrl)" :src="item.imgUrl" mode="aspectFill"></image>
				<image @click="delCoverImg(index)" src="../../static/images/delete-goods.svg" mode="aspectFit"></image>
			</view>
			<!-- 点击上传的加号 -->
			<view @click="uploadImg">
				<image src="../../static/images/attribute-img.png" mode="aspectFill"></image>
			</view>
		</view>
	</view>

	<!-- 上传短视频 -->
	<view class="goods-top goods-video">
		<!-- 标题部分 -->
		<view class="video-title">
			<text>上传短视频（可选）</text>
			<!-- 删除图标 -->
			<image @click="delVideo" v-if="video!=''" src="../../static/images/delete.svg" mode=""></image>
		</view>
		
		<!-- 上传图片的加号 -->
		<view class="goods-image" v-if="video ==''">
			<view @click="uploadVideo">
				<image src="../../static/images/attribute-img.png" mode="aspectFill"></image>
			</view>
		</view>
		<!-- 上传的视频展示 -->
		<video v-if="video!=''" :src="video" object-fit="cover"></video>
	</view>

	<!-- 所属分类 -->
	<view class="specs-view">
		<picker mode="selector" :range="classifyArr" range-key="sort_name" @change="pickerChange" >
			<view class="sort-title specs-title">
				<text>所属分类</text>
				<text>{{selectClassifyName}}</text>
				<image src="../../static/images/right-arrow.svg" mode="widthFix"></image>
			</view>
		</picker>
	</view>

	<!-- 价格、库存 (用于用户端显示 商品最低价格以及总库存 吸引顾客) -->
	<view class="specs-view price-stock">
		<view class="">
			<text>价格</text>
			<input type="number" v-model="price" :disabled="data.specs.length > 0 ? true : false" placeholder="请输入价格" placeholder-class="input-style" cursor-spacing="50">
			<text>元</text>
		</view>
		<view class="">
			<text>库存</text>
			<input type="number" v-model="stock" :disabled="data.specs.length > 0 ? true : false" placeholder="请输入库存" placeholder-class="input-style" cursor-spacing="50">
			<text>件</text>
		</view>
	</view>

	<!-- 创建规格  -->
	<view class="specs-view" @click="goSpecs">
		<!-- 标题 -->
		<view class="specs-title">
			<text>创建规格（可选）</text>
			<image src="../../static/images/right-arrow.svg" mode="widthFix"></image>
		</view>
		<!-- 点击添加规格 -->
		<view class="specs-image" v-if="data.specs.length==0">
			<image src="../../static/images/specification.jpg" mode="widthFix"></image>
		</view>

		<!-- 添加了规格之后展示 -->
		<view class="sku-specs sku-flex" v-if="data.specs.length > 0" v-for="(item,index) in data.specs" :key="index">
			<!-- 规格的图片展示 -->
			<view>
				<image :src="item.imgUrl" mode="aspectFill"></image>
			</view>
			<view class="sku-top">
				<view class="sku-flex sku-right">
					<text v-for="(item2,index2) in item.attribute" :key="index2">{{item2.att_val}}</text>
				</view>
				<view class="sku-flex sku-right sku-stock">
					<text>库存</text>
					<text>{{item.stock}}件</text>
				</view>
			</view>

			<!-- 价格 -->
			<view class="sku-price">￥{{item.price}}</view>
		</view>
	</view>

	<!-- 商品详情 -->
	<view class="specs-view">
		<!-- 标题 -->
		<view class="specs-title">
			<text>商品详情</text>
		</view>
		<!-- 图片 -->
		<view class=".detail-image" v-for="(item,index) in detailImg" :key="index" v-if="detailImg.length>0">
			<image :src="item.imgUrl" mode="widthFix" @click="previewDetail(item.imgUrl)"></image>
			<!-- 删除 -->
			<image @click="delDetail(index)" src="../../static/images/delete-goods.svg" mode="widthFix"></image>
		</view>
		<!-- 上传图片的按钮 -->
		<view class="specs-image" @click="uploadDetail">
			<image src="../../static/images/video-img.jpg" mode="widthFix"></image>
		</view>
	</view>

	<!-- 底部上架售卖按钮 -->
	<view style="height:200rpx"></view>
	<view class="bottom-button-position back">
		<view class="bottom-button-style" @click="putOnSale">上架售卖</view>
	</view>

</template>

<script setup>
	import { reactive, toRefs, watch, onMounted } from "vue"
	import { skuValue } from "../../public/package-js/passValue.js"
	import { Upload } from "@/public/package-js/uploadImg.js"
	import { FeedBack } from "@/public/package-js/feedBack.js"
	import { init } from "@/public/package-js/init.js"

	const data = reactive({ 
		specs: [], // 用于接收创建规格页面传递的值
		price: '', // 创建规格的价格最小值
		stock: '', // 总库存
		goods_title: '', //商品标题
		coverImg: [], //上传商品封面图片的链接数组
		video: '', //上传视频的链接
		classifyArr: [], // 分类列表
		selectClassifyName: '', //选中的所属分类
		selectClassifyId: '', // 选择分类的id，用以提交数据时对数据库分类所属商品数量quantity进行增加
		detailImg: [], // 商品详情图
	})
	const { price, stock, coverImg, goods_title, video, classifyArr, selectClassifyName, detailImg } = toRefs(data)

	// 从数据库获取所属分类
	onMounted(async () => {
		let db = await init()
		const res = await db.database().collection("goods_sort").field({
			_openid: false // 不让 _openid 返回到控制台
		}).get()
		// console.log("res",res);
		data.classifyArr = res.data
	})

	// 1、点击跳转规格页面
	function goSpecs() {
		let arr = JSON.stringify(data.specs)
		uni.navigateTo({
			url: '/pages/specs/specs?sku=' + arr
		});
	}
	// 2、使用侦听器监听 创建规格后返回上一页面的值 skuValue
	watch(skuValue, (newVal, oldVal) => {
		// console.log("newVal",newVal);
		data.specs = newVal
		// 取规格里面价格最小的进行封面展示
		let specsArr = JSON.parse(JSON.stringify(data.specs))
		let sortPrice = specsArr.sort((x, y) => {
			return x.price - y.price
		})
		let minPrice = sortPrice[0].price
		data.price = minPrice

		// 计算总库存
		let stockSum = 0
		specsArr.forEach((item, index) => {
			stockSum = stockSum + item.stock
		})
		data.stock = stockSum
	})

	// 3、点击上传封面图片
	async function uploadImg() {
		let local = await new Upload().image(9, "image") // 设置可以传九张图片
		local.forEach(item => {
			data.coverImg.push({ imgUrl: item.tempFilePath })
		})
		console.log("local",local);
	}

	// 4、点击删除商品封面图片
	function delCoverImg(index) {
		uni.showModal({
			title: '提示',
			content: '确定删除该图片吗？',
			success: async function(res) {
				if (res.confirm) {
					// 删除图片
					data.coverImg.splice(index, 1)
					new FeedBack("删除成功", "success").toast()
				} else if (res.cancel) {
					new FeedBack("取消操作", "error").toast()
				}
			}
		});
	}

	// 5、预览图片
	function previewImg(imgUrl) {
		// 因为预览图片的 arr 是 ["http:XXX","http:XX"] 字符串数组格式，所以进行转化
		let imgArr = []
		data.coverImg.forEach(item => {
			imgArr.push(item.imgUrl)
		})
		new Upload().preview(imgUrl, imgArr)
	}

	// 6、本地上传短视频
	async function uploadVideo() {
		let local = await new Upload().image(1, "video")
		// console.log("local",local);
		data.video = local[0].tempFilePath
	}

	// 7、删除短视频
	function delVideo() {
		uni.showModal({
			title: '提示',
			content: '确定删除该视频吗？',
			success: async function(res) {
				if (res.confirm) {
					// 删除视频
					data.video = ''
					new FeedBack("删除成功", "success").toast()
				} else if (res.cancel) {
					new FeedBack("取消操作", "error").toast()
				}
			}
		});
	}

	// 8、从数据库获取所属分类后，形成分类的选择器
	function pickerChange(e) {
		// console.log("e",data.classifyArr[e.detail.value]);
		data.selectClassifyName = data.classifyArr[e.detail.value].sort_name
		data.selectClassifyId = data.classifyArr[e.detail.value]._id
	}

	// 9、上传商品详情图
	async function uploadDetail() {
		let local = await new Upload().image(9, "image") // 设置可以传九张图片
		local.forEach(item => {
			data.detailImg.push({ imgUrl: item.tempFilePath })
		})
		// console.log("详情图片",local);
	}

	// 10、删除详情图
	function delDetail(index) {
		uni.showModal({
			title: '提示',
			content: '确定删除该详情图吗？',
			success: async function(res) {
				if (res.confirm) {
					// 删除视频
					data.detailImg.splice(index, 1)
					new FeedBack("删除成功", "success").toast()
				} else if (res.cancel) {
					new FeedBack("取消操作", "error").toast()
				}
			}
		});
	}

	// 11、预览详情图
	function previewDetail(imgUrl) {
		// 因为预览图片的 arr 是 ["http:XXX","http:XX"] 字符串数组格式，所以进行转化
		let imgArr = []
		data.detailImg.forEach(item => {
			imgArr.push(item.imgUrl)
		})
		new Upload().preview(imgUrl, imgArr)
	}

	// 12、点击上架售卖
	function putOnSale() {
		// 校验
		switch (true) {
			case data.goods_title == '':
				new FeedBack("请填写标题", "error").toast()
				break;
			case data.coverImg.length == 0:
				new FeedBack("请上传封面图片", "error").toast()
				break;
			case data.selectClassifyName == '':
				new FeedBack("请选择分类", "error").toast()
				break;
			case data.price == '':
				new FeedBack("请输入价格", "error").toast()
				break;
			case data.stock == '':
				new FeedBack("请输入库存", "error").toast()
				break;
			case data.detailImg.length == 0:
				new FeedBack("请上传详情图片", "error").toast()
				break;
			default:
				commit() // 校验通过调用提交方法
				break;
		}
	}

	// 12-1 将数据提交到数据库
	async function commit() {
		uni.showLoading({
			title: '上传中',
			mask: true
		});

		// (1) 上传横幅图片
		let bannerRes = await new Upload().multiUpload(data.coverImg, "image")
		// console.log("上传",bannerRes);

		// (2) 上传详情图
		let deatilRes = await new Upload().multiUpload(data.detailImg, "image")

		// (3) 上传短视频（有的话就上传）
		let videoUrl = '';
		if (data.video == '') {
			videoUrl = ''
		} else {
			let videoRes = await new Upload().cloud(data.video)
			videoUrl = videoRes.tempFileURL
		}
		
		// console.log("333333",videoUrl);

		// 将填写好的商品信息进行组装
		let obj = {
			goods_title: data.goods_title,
			goods_banner: bannerRes, // 上传商品封面图片的链接数组
			goods_cover: bannerRes[0].image, // '商品封面图,商品横幅的第一张图片作为封面图'
			video_url: videoUrl, //'短视频链接'
			category: data.selectClassifyName, //'所属分类'
			goods_price: Number(data.price), //商品价格
			stock: Number(data.stock), //总库存
			sku: data.specs.length == 0 ? false : true, //是否有sku规格
			goods_details: deatilRes, // 上传云端的商品详情图
			sold: 0, // 商品已售多少
			shelves: true, //商品上架与否 true or false
			seckill: false, //该商品是否参与秒杀 true or false
		}


		// 设计规格数据库，将商品id和规格关联起来
		// 上传到数据库
		try {
			let db = await init()
			const res = await db.database().collection("goods").add({
				data: obj
			})
			// console.log("shang", res);

			// 获取返回的 _id，上传商品规格
			if (data.specs.length > 0) {
				await db.database().collection("sku_data").add({
					data: {
						sku_id: res._id,
						sku: data.specs
					}
				})
			}
			// 对选择的分类下商品数量 ++ (自增)
			const _ = db.database().command
			await db.database().collection('goods_sort').doc(data.selectClassifyId).update({
				data: {
					quantity: _.inc(1)
				}
			})
			// 上传成功后隐藏加载
			new FeedBack("上传成功", "success").toast()

			// 置空页面
			data.specs = []
			data.price = ''
			data.price = '' // 创建规格的价格最小值
			data.stock = '' // 总库存
			data.goods_title = '' //商品标题
			data.coverImg = [] //上传商品封面图片的链接数组
			data.video = '' //上传视频的链接
			data.classifyArr = [] // 分类列表
			data.selectClassifyName = '' //选中的所属分类
			data.selectClassifyId = '' // 选择分类的id，用以提交数据时对数据库分类所属商品数量quantity进行增加
			data.detailImg = [] // 商品详情图

			// 跳转页面
			uni.switchTab({
				url: "/pages/commodity/commodity"
			})

		} catch (e) {
			new FeedBack("上传失败", "error").toast()
		}
	}
</script>

<style>
	page {
		background-color: #f2f2f2;
	}
	
	.goods-top {
		background-color: #FFFFFF;
		padding: 20rpx;
	}

	.goods-top input {
		padding: 30rpx 0;
		font-weight: bold;
	}

	.pl-text {
		/* 输入框提示语样式 */
		font-weight: 100;
	}

	.goods-image {
		display: flex;
		flex-wrap: wrap;
	}

	.goods-image view {
		width: calc(33.3% - 5rpx*2);
		height: 200rpx;
		margin: 5rpx;
	}

	.goods-image image {
		width: 100%;
		height: 100%;
		display: block;
		border-radius: 7rpx;
	}

	.upload-image {
		position: relative;
	}

	.upload-image image:nth-child(2) {
		width: 30rpx !important;
		height: 30rpx !important;
		position: absolute;
		top: 6rpx;
		right: 6rpx;
	}

	/* 视频 */
	.goods-video {
		margin-top: 40rpx;
		font-weight: bold;
	}

	.video-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.video-title image {
		width: 38rpx;
		height: 38rpx;
		display: block;
	}

	.goods-video video {
		height: 400rpx;
		width: 100%;
	}

	/* 所属分类 */
	.sort-title text:nth-child(1) {
		flex: 1;
	}

	.sort-title text:nth-child(2) {
		padding-right: 20rpx;
	}

	/* 价格，库存 */
	.price-stock view {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
	}

	.price-stock view:nth-child(1) {
		padding-bottom: 20rpx;
	}

	.price-stock text:nth-child(1) {
		flex: 1;
	}

	.price-stock input {
		padding: 0 20rpx;
		text-align: right;
	}

	.input-style {
		color: #a8a8a8;
		font-size: 28rpx !important;
	}

	/* 规格 */
	.specs-view {
		background-color: #FFFFFF;
		margin: 40rpx 20rpx;
		border-radius: 8rpx;
	}

	.specs-title image {
		width: 35rpx;
		height: 35rpx;
		display: block;
	}

	.specs-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		font-weight: bold;
	}

	.specs-image {
		padding: 20rpx;
	}

	.specs-image image {
		width: 100%;
		height: 100%;
		display: block;
		border-radius: 8rpx;
	}



	/* 详情图片样式 */
	.detail-image {
		position: relative;
		padding: 20rpx 20rpx 0 20rpx;

	}

	.detail-image image:nth-child(1) {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
		display: block;
	}

	.detail-image image:nth-child(2) {
		width: 40rpx;
		height: 40rpx;
		position: absolute;
		top: 40rpx;
		right: 35rpx;
	}

	/* 已选规格 */
	.sku-flex {
		display: flex;
		align-items: center;
	}

	.sku-flex image {
		width: 100rpx;
		height: 100rpx;
		display: block;
		border-radius: 8rpx;
	}

	.sku-specs {
		padding: 20rpx;
		border-bottom: 1rpx solid #e6e6e6;
	}

	.sku-top {
		flex: 1;
	}

	.sku-top view:nth-child(1) {
		padding-bottom: 10rpx;
	}

	.sku-right text {
		padding: 0 20rpx;
	}

	.sku-stock {
		color: #c3c3c3;
	}

	.sku-price {
		font-weight: bold;
	}

	/* 底部 */
	.back {
		background-color: #fafafa !important;
		padding-top: 20rpx !important;
	}
</style>
